﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Site3AI.Models
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class DateValidationAttribute : ValidationAttribute
    {        
        private DateValidationAttribute(DateTime beginDate, string errorMessageFormat)
        {
            this.BeginDate = beginDate;
            this.EndDate = DateTime.UtcNow.AddDays(2); //System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "China Standard Time").Date.AddDays(2);
            this.ErrorMessageFormat = !String.IsNullOrEmpty(errorMessageFormat) ? errorMessageFormat
                : "{0}必须在" + beginDate.ToString("yyyy-MM-dd") + "到" + this.EndDate.ToString("yyyy-MM-dd") + "之间";
        }

        public DateValidationAttribute(string strBeginDate, string errorMessageFormat)
            : this(DateTime.Parse(strBeginDate), errorMessageFormat)
        {

        }

        public DateValidationAttribute(string strBeginDate)
            : this(strBeginDate, null)
        {

        }

        public DateTime BeginDate { get; set; }

        public DateTime EndDate { get; set; }

        public string ErrorMessageFormat { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime dateValue = (DateTime)value;
            if (dateValue.Date < this.BeginDate.Date || dateValue.Date > this.EndDate.Date)
            {
                return new ValidationResult(String.Format(this.ErrorMessageFormat, validationContext.DisplayName));
            }
            return ValidationResult.Success;
        }
    }
}